package com.untrance.shop.common.utils;

import com.untrance.shop.common.filters.model.PaginableFilter;
import com.untrance.shop.common.vo.PagerParametersVO;

/**
 * @author eugene zadyra
 */
public class PagerUtils {

	private static int NUMBERS_COUNT = 5;

	public static PagerParametersVO calculatePagerParameters(int page, int count, int itemsPerPage) {
		int pagesCount = (int) Math.ceil((double) count / (double) itemsPerPage);
		if (pagesCount < 1) {
			pagesCount = 1;
		}

		int currentPage = page;
		if (currentPage > pagesCount) {
			currentPage = pagesCount;
		}
		int begin = 1;
		int end = NUMBERS_COUNT;

		if (currentPage > 3) {
			if ((currentPage + (int) (NUMBERS_COUNT / 2)) <= pagesCount) {
				begin = currentPage - (int) (NUMBERS_COUNT / 2);
				end = currentPage + (int) (NUMBERS_COUNT / 2);
			} else {
				begin = pagesCount - (NUMBERS_COUNT - 1);
				end = pagesCount;
			}
		} else if (pagesCount < NUMBERS_COUNT) {
			end = pagesCount;
		}
		if (begin < 1) {
			begin = 1;
		}
		return new PagerParametersVO(begin, end, pagesCount, currentPage, count);
	}

	public static Integer calculateFirstElement(Integer page, Integer itemsPerPage) {
		if (page == null)
			return null;
		if (itemsPerPage == null) {
			itemsPerPage = 12;
		} else if (itemsPerPage > 100) {
			itemsPerPage = 100;
		}
		return itemsPerPage * (page - 1);
	}

	public static <T extends PaginableFilter> T updateFilterPaginationInfo(T filter, Integer page, Integer itemsPerPage) {
		if (itemsPerPage == null) {
			itemsPerPage = 12;
		} else if (itemsPerPage > 100) {
			itemsPerPage = 100;
		}
		Integer from = PagerUtils.calculateFirstElement(page, itemsPerPage);
		filter.setFirstResult(from);
		filter.setItemsPerPage(itemsPerPage);
		return filter;
	}
}
